<script setup>
import { ref, watch } from 'vue'
import BasePieChart from '@/components/chart/BasePieChart.vue'
import CustomDateRadio from '@/components/header/CustomDateRadio.vue'
import { useAreaStore } from '@/stores/area'
import { useCompanyStore } from '@/stores/company'
import { getAllAreaReportApi } from '@/api/area'

const props = defineProps({
    title: {
        type: String,
        default: '区域用电量'
    },
    height: {
        type: String,
        default: '230px'
    }
})

const areaStore = useAreaStore()
const companyStore = useCompanyStore()

// 饼图数据和时间控制
const pieChartTime = ref(null)
const pieChartData = ref([])

// 获取区域总数据的方法
async function getAreaTotalData() {
    if (!pieChartTime.value || !companyStore.currentCompany?.id) return

    try {
        const res = await getAllAreaReportApi({
            id: companyStore.currentCompany.id,
            start_time: pieChartTime.value.start_time,
            end_time: pieChartTime.value.end_time,
            type: 2, // 用电类型
        })

        if (res.aggregated_data) {
            pieChartData.value = res.aggregated_data.flat().map(item => ({
                name: areaStore.getAreaNameById(item.area_id),
                value: Number(item.usage),
                area_id: item.area_id
            })).sort((a, b) => b.value - a.value)
        }
    } catch (error) {
        console.error('获取区域用电数据失败:', error)
        pieChartData.value = []
    }
}

// 监听时间变化
watch(() => pieChartTime.value, getAreaTotalData, { immediate: true })

// 监听公司变化
watch(() => companyStore.currentCompany, getAreaTotalData, { immediate: true })
</script>

<template>
    <div class="card-header">
        <span>{{ title }}</span>
        <CustomDateRadio @update:modelValue="pieChartTime = $event"></CustomDateRadio>
    </div>
    <BasePieChart :height="height" :showLegend="false" :data="pieChartData" unit="kwh" />
</template>

<style scoped>
.area-electricity-usage {
    height: 100%;
}
</style>